package com.ruoyi.aftersale.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.aftersale.domain.DmsRepairOrder;
import com.ruoyi.aftersale.domain.DmsRepairReservation;
import com.ruoyi.aftersale.mapper.DmsRepairOrderMapper;
import com.ruoyi.aftersale.service.IDmsRepairOrderService;
import com.ruoyi.aftersale.service.IDmsRepairReservationService;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.AutofillUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.SerialNumberGenerator;
import com.ruoyi.fund.domain.DmsFund;
import com.ruoyi.fund.service.IDmsFundService;
import com.ruoyi.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 维修工单Service业务层处理
 * 
 * @author liuchuanfa
 * @date 2024-03-13
 */
@Service
public class DmsRepairOrderServiceImpl extends ServiceImpl<DmsRepairOrderMapper,DmsRepairOrder> implements IDmsRepairOrderService
{
    @Autowired
    private DmsRepairOrderMapper dmsRepairOrderMapper;
    @Autowired
    private AutofillUtil autofillUtil;
    @Autowired
    private IDmsRepairReservationService iDmsRepairReservationService;
    @Autowired
    private IDmsFundService iDmsFundService;
    @Autowired
    private ISysDeptService iSysDeptService;
    @Autowired
    SerialNumberGenerator serialNumberGenerator;

    /**
     * 查询维修工单
     * 
     * @param id 维修工单主键
     * @return 维修工单
     */
    @Override
    public DmsRepairOrder selectDmsRepairOrderById(Long id)
    {
        return dmsRepairOrderMapper.selectDmsRepairOrderById(id);
    }

    /**
     * 查询维修工单列表
     * 
     * @param dmsRepairOrder 维修工单
     * @return 维修工单
     */
    @Override
    public List<DmsRepairOrder> selectDmsRepairOrderList(DmsRepairOrder dmsRepairOrder)
    {
        return dmsRepairOrderMapper.selectDmsRepairOrderList(dmsRepairOrder);
    }

    /**
     * 新增维修工单
     * 
     * @param dmsRepairOrder 维修工单
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertDmsRepairOrder(DmsRepairOrder dmsRepairOrder)
    {
        //1.插入工单
        //判断工单新建状态只能为待派工
        if (!dmsRepairOrder.getStatus().equals(1)){
            throw new ServiceException("维修工单创建时的状态只能是 待派工！");
        }
        //若未输入工单编号则后台自动生成
        if (StrUtil.isBlank(dmsRepairOrder.getRoNo())){
            dmsRepairOrder.setRoNo(serialNumberGenerator.generateSerialNumber("GDBH"));
        }
        //新增自动填充
        autofillUtil.autoFillCreate(dmsRepairOrder);
        //填充经销商id 经销商名称
        dmsRepairOrder.setDealerId(SecurityUtils.getLoginUser().getUser().getDept().getParentId());
        dmsRepairOrder.setDealerName(iSysDeptService.selectDeptById(SecurityUtils.getLoginUser().getUser().getDept().getParentId()).getDeptName());
        dmsRepairOrderMapper.insertDmsRepairOrder(dmsRepairOrder);

        //2.向预约单中插入工单编号
        iDmsRepairReservationService.lambdaUpdate()
                .set(DmsRepairReservation::getRoId,dmsRepairOrder.getId())
                .eq(DmsRepairReservation::getReservationNo,dmsRepairOrder.getReservationNo())
                .update();
        return 1;
    }

    /**
     * 修改维修工单
     * 
     * @param dmsRepairOrder 维修工单
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateDmsRepairOrder(DmsRepairOrder dmsRepairOrder)
    {
        //判断金额是负数吗
        if (dmsRepairOrder.getLabourPrice()<0 || dmsRepairOrder.getTotalAmount()<0 || dmsRepairOrder.getIncomingOilLevel()<0 || dmsRepairOrder.getInMileage()<0){
            throw new ServiceException("数字只能为非负数");
        }

        //判断状态不能扭转
        Integer states = dmsRepairOrder.getStatus();
        DmsRepairOrder dmsRepairOrderDB = selectDmsRepairOrderById(dmsRepairOrder.getId());
        Integer statesDB = dmsRepairOrderDB.getStatus();
        //如果要变成已作废，则通过。否则只有状态逐级递增，其他情况不允许状态跨越和逆转
        if (!states.equals(6) && (states-statesDB != 1)){
            throw new ServiceException("工单状态不允许逆转 与 跨级！");
        }
        //修改时自动填充
        autofillUtil.autoFillUpdate(dmsRepairOrder);
        //填充审核人id 审核人名称 审核时间
        //填充审核人、审核名称、审核时间
        dmsRepairOrder.setAuditorId(SecurityUtils.getLoginUser().getUser().getUserId());
        dmsRepairOrder.setAuditorName(SecurityUtils.getLoginUser().getUser().getUserName());
        dmsRepairOrder.setAuditorTime(new Date());
        dmsRepairOrderMapper.updateDmsRepairOrder(dmsRepairOrder);

        //如果工单结算的话，还需要去修改资金表、预约单状态（服务结束）
        if (dmsRepairOrder.getStatus().equals(5)){
            //资金表加钱
            DmsFund dmsFund = iDmsFundService.lambdaQuery().eq(DmsFund::getFundOwnerId, SecurityUtils.getLoginUser().getUser().getDept().getParentId()).one();
            dmsFund.setFund(dmsFund.getFund() + dmsRepairOrder.getTotalAmount());
            iDmsFundService.updateDmsFund(dmsFund);

            //预约单状态改为已完成
            iDmsRepairReservationService.lambdaUpdate()
                    .set(DmsRepairReservation::getStates,3)
                    .eq(DmsRepairReservation::getReservationNo,dmsRepairOrder.getReservationNo())
                    .update();
        }
        return 1;
    }

    /**
     * 批量删除维修工单
     * 
     * @param ids 需要删除的维修工单主键
     * @return 结果
     */
    @Override
    public int deleteDmsRepairOrderByIds(Long[] ids)
    {
        return dmsRepairOrderMapper.deleteDmsRepairOrderByIds(ids);
    }

    /**
     * 删除维修工单信息
     * 
     * @param id 维修工单主键
     * @return 结果
     */
    @Override
    public int deleteDmsRepairOrderById(Long id)
    {
        return dmsRepairOrderMapper.deleteDmsRepairOrderById(id);
    }
}
